package com.example.zqq.fivechess.five_ai;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zqq.fivechess.FiveChessView;
import com.example.zqq.fivechess.GameCallBack;
import com.example.zqq.fivechess.R;

public class Main2Activity extends AppCompatActivity implements AICallBack, GameCallBack, View.OnClickListener {

    private FiveAIChessView fiveAIChessView;    //五子棋UI
    private TextView userScoreTv, aiScoreTv;    //显示用户以及ai得分
    private ImageView userChessIv, aiChessIv;    //显示玩家/ai执子
    private ImageView userTimeIv, aiTimeIv;     //玩家/ai回合标识

    private AI ai;                              //游戏ai
    private PopupWindow chooseChess;            //PopUpWindow选择玩家执子


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_ai);

        //初始化控件
        initViews();

        //初始化ai
        ai = new AI(fiveAIChessView.getChessArray(), this);

        //view加载完成
        /*  注册一个回调函数，当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时调用这个回调函数。
         *  参数 listener    将要被添加的回调函数
         *  异常 IllegalStateException       如果isAlive() 返回false
         */
        fiveAIChessView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //初始化PopupWindow
                WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                initPop(manager.getDefaultDisplay().getWidth(), manager.getDefaultDisplay().getHeight());
            }
        });
    }

    //初始化
    private void initViews() {
        //五子棋UI
        fiveAIChessView = (FiveAIChessView) findViewById(R.id.five_chess_view);
        fiveAIChessView.setCallBack(this);

        //显示用户以及ai得分
        userScoreTv = (TextView) findViewById(R.id.user_score_tv);
        aiScoreTv = (TextView) findViewById(R.id.ai_score_tv);

        //显示玩家/ai执子
        userChessIv = (ImageView) findViewById(R.id.user_chess_iv);
        aiChessIv = (ImageView) findViewById(R.id.ai_chess_iv);
        //玩家/ai回合标识
        userTimeIv = (ImageView) findViewById(R.id.user_think_iv);
        aiTimeIv = (ImageView) findViewById(R.id.ai_think_iv);
        //重开游戏设置点击事件
        findViewById(R.id.restart_game).setOnClickListener(this);
    }


    //初始化PopupWindow
    private void initPop(int width, int height) {
        if (chooseChess == null) {
            View view = View.inflate(this, R.layout.popupwindow, null);
            ImageButton white = view.findViewById(R.id.choose_white);
            ImageButton black = view.findViewById(R.id.choose_black);

            white.setOnClickListener(this);
            black.setOnClickListener(this);

            chooseChess = new PopupWindow(view, width, height);
            chooseChess.setOutsideTouchable(false);
            chooseChess.showAtLocation(fiveAIChessView, Gravity.CENTER, 0, 0);
        }
    }

    //更新游戏胜利局数
    private void updateWinInfo() {
        userScoreTv.setText(fiveAIChessView.getUserScore() + " ");
        aiScoreTv.setText(fiveAIChessView.getAiScore()+" ");
    }

    private void showToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    /**********------AICallBack----***********/
    @Override
    public void aiAtTheBell() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI
                fiveAIChessView.postInvalidate();

                //检查游戏是否结束
                fiveAIChessView.checkAiGameOver();

                //设置为玩家回合
                fiveAIChessView.setUserBout(true);

                //更改当前落子
                aiTimeIv.setVisibility(View.GONE);
                userTimeIv.setVisibility(View.VISIBLE);
            }
        });
    }

    /**********------GameCallBack----***********/
    @Override
    public void GameOver(int winner) {
        //更新游戏胜利局数
        updateWinInfo();
        switch (winner) {
            case FiveAIChessView.BLACK_WIN:
                showToast("黑棋胜利！");
                break;
            case FiveChessView.NO_WIN:
                showToast("平局！");
                break;
            case FiveChessView.WHITE_WIN:
                showToast("白棋胜利！");
                break;
        }
    }



    @Override
    public void ChangeGamer(boolean isWhite) {
        //ai回合
        ai.aiBout();

        //更改当前落子
        aiTimeIv.setVisibility(View.VISIBLE);
        userTimeIv.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.restart_game:
                //显示PopupWindow
                chooseChess.showAtLocation(fiveAIChessView, Gravity.CENTER, 0, 0);

                //重新开始游戏
                fiveAIChessView.resetGame();
                break;
            case R.id.choose_black:
                changeUI(false);
                chooseChess.dismiss();
                break;
            case R.id.choose_white:
                changeUI(true);
                chooseChess.dismiss();
                break;
        }
    }

    //根据玩家选择执子，更新UI
    private void changeUI(boolean isUserWhite) {
        if (isUserWhite) {
            //玩家选择白棋
            fiveAIChessView.setUserChess(FiveAIChessView.WHITE_CHESS);
            ai.setAiChess(FiveAIChessView.BLACK_CHESS);

            //玩家先手
            fiveAIChessView.setUserBout(true);      //是否是玩家的回合

            //更改当前视图-棋子代表
            userChessIv.setBackgroundResource(R.mipmap.stone_w2);
            aiChessIv.setBackgroundResource(R.mipmap.stone_b1);

            aiTimeIv.setVisibility(View.GONE);
            userTimeIv.setVisibility(View.VISIBLE);

        } else {
            //玩家选择黑棋
            fiveAIChessView.setUserChess(FiveAIChessView.BLACK_CHESS);
            fiveAIChessView.setUserBout(false);         //是否是玩家的回合

            //ai先手
            ai.setAiChess(FiveAIChessView.WHITE_CHESS);
            ai.aiBout();

            //更改当前视图-棋子代表
            userChessIv.setBackgroundResource(R.mipmap.stone_b1);
            aiChessIv.setBackgroundResource(R.mipmap.stone_w2);
            aiTimeIv.setVisibility(View.VISIBLE);
            userTimeIv.setVisibility(View.GONE);
        }
    }

}
